<template>
  <div class="demo3_page">
    <van-nav-bar
      title="测试demo4--防抖按钮"
      left-arrow
      @click-left="handleLeavePage"
    />

    <van-form @submit="onSubmit" @failed="onFailed" ref="formBox" scroll-to-error >
      <van-field autocomplete="off"
        v-model="name"
        name="name"
        label="用户名"
        placeholder="请输入用户名"
        required
        :rules="[{ required: true, message: '请输入正确内容' }]"
      />
      <van-field autocomplete="off"
        v-model="pwd"
        type="password"
        name="pwd"
        label="密码"
        placeholder="请输入密码"
        required
        :rules="[{ required: true, message: '请输入正确内容' }]"
      />


      <!--  一定要写在form组件里面    -->
      <DebounceSubmitBtn :isSubmitBtnDisabled="isSubmitBtnDisabled" />
    </van-form>

  </div>
</template>

<script>
import {mixin_btnStatus} from "../../mixin/mixin_btn";
import DebounceSubmitBtn from "../../components/DebounceSubmitBtn";
import {Toast, Dialog} from "vant";
export default {
  name: "demo4",
  mixins: [mixin_btnStatus],
  components: {
    DebounceSubmitBtn,
  },
  data() {
    return {
      name: '',
      pwd: '',
    };
  },

  mounted() {
    /*
    * 核心： 使用ref="formBox"，getValues()方法
    *
    * */
    // console.error('实例对象', this.$refs.formBox);
    console.log('实例对象-----getValues()方法', this.$refs.formBox.getValues())
    this.timerId = setInterval(()=>{
      // todo 实现草稿箱功能
      // 获取表单的全部值
      const values =  this.$refs.formBox.getValues();
      console.log('表单数值', values);
      const formVal_draft = this._getFormVal(values);
      console.warn('500毫秒----不断实时执行-----拼接后的参数(后端需要的字段)----草稿值', formVal_draft);
      localStorage.setItem('draft_publish_demo', JSON.stringify(formVal_draft));
    }, 500);
  },

  beforeDestroy() {
    // 清除循环定时器
    clearInterval(this.timerId);
  },

  methods: {

    handleLeavePage(){
      Dialog.confirm({
        message: '保存此次编辑？',
        confirmButtonText: '保存',
        cancelButtonText: '不保存',
      })
        .then(() => {
          // 发送请求保存到数据库
          this.$router.back();
        })
        .catch(() => {
          // 不报存
          this.$router.back();
        });
    },
    // 将表单收集到的数据抽离出来，用于拼接为后端需要的字段
    _getFormVal(values){

      const {
        name,
        pwd
      } = values;

      // 拼接、组合接口需要的参数
      const params = {
        // 转发或者发布
        username: name,
        passWd: pwd
      };


      return params;


    },


    // 提交
    onSubmit(values) {
      console.log('表单值----成功', values);
      const paramObj = this._getFormVal(values);
    },


    onFailed({values}){
      Toast('填写的信息可能有误！请上、下滑动进行检查。')
    },

  },
}
</script>

<style scoped>

</style>
